package mxc

import (
	"errors"
	"fmt"
	"gitee.com/jinmingzhi/block-chain-news/model"
	"github.com/antchfx/htmlquery"
	"go.uber.org/zap"
	"time"
)

const url = "https://support.mxc-exchange.com/hc/zh-cn/sections/360000547811-%E6%96%B0%E5%B8%81%E4%B8%8A%E7%BA%BF"

type mxc struct {
	name       string
	newArticle string
	timer      time.Duration
}

func NewMxc(t time.Duration) *mxc {
	return &mxc{
		name:       "mxc(抹茶)",
		newArticle: "",
		timer:      t,
	}
}

func (h *mxc) Monitor(articleChan chan<- model.Msg) {
	h.newArticle, _ = getArticle()
	log.Info(fmt.Sprintf("%s: %s", h.name, h.newArticle))

	go func() {
		t := time.NewTicker(h.timer)
		for range t.C {
			str, err := getArticle()
			if err != nil {
				continue
			}
			if str != h.newArticle {
				h.newArticle = str
				articleChan <- model.Msg{OriginName: h.name, Text: str}
			}
		}
	}()
}

func getArticle() (s string, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = errors.New(fmt.Sprintf("%v", e))
		}
	}()
	doc, err := htmlquery.LoadURL(url)
	if err != nil {
		log.Error("failed to load url", zap.String("url", url), zap.Error(err))
		return "", err
	}
	node := htmlquery.FindOne(doc, `//main/div[2]/div/section/ul/li[1]/a`)
	return htmlquery.InnerText(node), nil
}
